package com.ncloud.system.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ncloud.common.utils.RedisUtils;
import com.ncloud.system.constant.UserConstant;
import com.ncloud.system.entity.UserAuth;
import com.ncloud.system.mapper.UserAuthMapper;
import com.ncloud.system.service.UserAuthService;

@Service
public class UserAuthServiceImpl implements UserAuthService {
	@Autowired
	private UserAuthMapper mapper;
	@Autowired
	private RedisUtils redisUtils;
	
	@Override
	public void save(UserAuth userAuth) {
		// 插入数据库
		mapper.save(userAuth);
		// 加载redis内存
		redisUtils.set(UserConstant.REDIS_USER_AUTH_PREFIX + userAuth.getAuthCode(),
				userAuth.getUserId(), UserConstant._USER_AUTH_EXPIRETIME);
	}

	@Override
	public void save(Long userId, String authCode) {
		// 失效其他认证码
		expireOtherAuthCode(userId);
		// 新生成认证码
		UserAuth userAuth = new UserAuth(userId,authCode);
		save(userAuth);
	}

	private void expireOtherAuthCode(Long userId) {
		List<UserAuth> auths = mapper.getAuthsByUserId(userId);
		for (int i = 0; auths!=null && i < auths.size(); i++) {
			UserAuth auth = auths.get(i);
			expire(auth.getAuthCode());
		}
	}

	@Override
	public void expire(String authCode) {
		redisUtils.remove(UserConstant.REDIS_USER_AUTH_PREFIX + authCode);
		mapper.expire(authCode);		
	}

}
